package com.xjust.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.xjust.pojo.Result;
import com.xjust.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class WebInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String token = request.getHeader("Authorization");
        log.info(token);
        //判断令牌是否存在
        if(token==null ){
            //返回错误信息
            Result result = new Result(0,"NOT_LOGIN",null);
            log.info("令牌未找到");
            String jsonStr = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonStr);
            return false;
        }
        //解析JSON
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析异常");
            Result result = new Result(0,"NOT_LOGIN",null);
            String jsonStr = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(jsonStr);
            return false;
        }
        //放行
        return true;
    }
}
